#!/bin/bash

# SPAM3UK Ubuntu交叉编译脚本
# 在macOS上编译适用于Ubuntu Linux的可执行文件

set -e

echo "🔨 SPAM3UK Ubuntu交叉编译"
echo "================================"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 检查Go环境
echo "1. 检查Go环境..."
if ! command -v go &> /dev/null; then
    echo -e "${RED}❌ Go未安装或不在PATH中${NC}"
    exit 1
fi

GO_VERSION=$(go version | awk '{print $3}')
echo -e "${GREEN}✅ Go版本: $GO_VERSION${NC}"

# 检查项目文件
echo -e "\n2. 检查项目文件..."
if [[ ! -f "main.go" ]]; then
    echo -e "${RED}❌ 未找到main.go文件${NC}"
    exit 1
fi

if [[ ! -f "go.mod" ]]; then
    echo -e "${RED}❌ 未找到go.mod文件${NC}"
    exit 1
fi

echo -e "${GREEN}✅ 项目文件检查通过${NC}"

# 清理依赖
echo -e "\n3. 清理和更新依赖..."
go mod tidy
go mod download
echo -e "${GREEN}✅ 依赖更新完成${NC}"

# 编译目标配置
TARGET_OS="linux"
TARGET_ARCH="amd64"
OUTPUT_NAME="spam3uk-ubuntu"

echo -e "\n4. 开始交叉编译..."
echo -e "${BLUE}目标系统: $TARGET_OS/$TARGET_ARCH${NC}"
echo -e "${BLUE}输出文件: $OUTPUT_NAME${NC}"

# 设置交叉编译环境变量并编译
GOOS=$TARGET_OS GOARCH=$TARGET_ARCH CGO_ENABLED=0 go build \
    -ldflags="-w -s -X main.Version=$(date +%Y%m%d-%H%M%S)" \
    -o $OUTPUT_NAME main.go

if [[ $? -eq 0 ]]; then
    echo -e "\n${GREEN}🎉 编译成功！${NC}"
    
    # 显示文件信息
    echo -e "\n5. 编译结果:"
    ls -lh $OUTPUT_NAME
    file $OUTPUT_NAME
    
    # 计算文件哈希
    echo -e "\n6. 文件校验:"
    if command -v sha256sum &> /dev/null; then
        sha256sum $OUTPUT_NAME
    elif command -v shasum &> /dev/null; then
        shasum -a 256 $OUTPUT_NAME
    fi
    
    echo -e "\n${GREEN}✅ Ubuntu可执行文件已生成: $OUTPUT_NAME${NC}"
    echo "================================"
    echo "📋 部署说明:"
    echo "1. 将 $OUTPUT_NAME 上传到Ubuntu服务器"
    echo "2. 将配置文件也一起上传:"
    echo "   - spam4uk-config.prod.json (生产配置)"
    echo "   - 或 spam3uk-config.json (默认配置)"
    echo "3. 在Ubuntu服务器上:"
    echo "   chmod +x $OUTPUT_NAME"
    echo "   ./$OUTPUT_NAME"
    echo ""
    echo "🌐 服务器部署命令:"
    echo "   scp $OUTPUT_NAME anders@118.145.200.164:/data/prod/spam3uk/"
    echo "   scp spam4uk-config.prod.json anders@118.145.200.164:/data/prod/spam3uk/"
    
else
    echo -e "\n${RED}❌ 编译失败${NC}"
    exit 1
fi

# 创建部署包
echo -e "\n7. 创建部署包..."
PACKAGE_NAME="spam3uk-ubuntu-$(date +%Y%m%d-%H%M%S).tar.gz"

tar -czf $PACKAGE_NAME \
    $OUTPUT_NAME \
    spam4uk-config.prod.template.json \
    deploy-prod.sh \
    rollback.sh \
    quick-start.sh \
    manage.sh \
    startup-guide.md \
    db_scripts/ \
    --exclude='*.log' \
    --exclude='.git*'

if [[ -f $PACKAGE_NAME ]]; then
    echo -e "${GREEN}✅ 部署包已创建: $PACKAGE_NAME${NC}"
    ls -lh $PACKAGE_NAME
    
    echo -e "\n📦 部署包内容:"
    tar -tzf $PACKAGE_NAME | head -20
    
    echo -e "\n🚀 一键部署命令:"
    echo "   scp $PACKAGE_NAME anders@118.145.200.164:/data/prod/"
    echo "   ssh anders@118.145.200.164"
    echo "   cd /data/prod && tar -xzf $PACKAGE_NAME"
    echo "   cd spam3uk && ./quick-start.sh"
fi

echo -e "\n${GREEN}🎯 编译和打包完成！${NC}"
